package com.demo.security.custom.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import com.demo.security.config.bean.RsaProperties;
import com.demo.security.model.SysUserDetails;
import com.demo.security.utils.JwtUtils;

// @Component
public class JwtTokenVerifyFilter extends BasicAuthenticationFilter {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    private RsaProperties rsaProperties;

    public JwtTokenVerifyFilter(AuthenticationManager authenticationManager, RsaProperties rsaProperties) {
        super(authenticationManager);
        this.rsaProperties = rsaProperties;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("在这里验证Authorization");
        // 判断请求体的头中是否包含Authorization
        String authorization = request.getHeader("Authorization");
        log.info("Authorization: {}", authorization);
        if (authorization != null && authorization.startsWith("Bearer ")) {
            // 从Token中获取用户信息保存到SpringSecurity上下文中
            authorization = authorization.replace("Bearer ", "");
            SysUserDetails sysUser = JwtUtils.getInfoFromToken(authorization, rsaProperties.getPublicKey(), SysUserDetails.class).getUserInfo();
            if (sysUser != null) {
                Authentication authResult = new UsernamePasswordAuthenticationToken(sysUser.getUsername(), sysUser.getPassword(), sysUser.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authResult);
            }
        }
        chain.doFilter(request, response);
    }
}
